package com.aabte.commons.util;

import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * @author Daniel
 */
public class ValidatorUtils {

    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static <T> Map<String, String> validate(T data, Class<?>... groups) {
        Validator validator = validatorFactory.getValidator();
        Set<ConstraintViolation<T>> validateResult = validator.validate(data, groups);
        if (validateResult.isEmpty()) {
            return new LinkedHashMap<>();
        } else {
            Map<String, String> errors = new LinkedHashMap<>();
            for (ConstraintViolation<T> violation : validateResult) {
                String message = violation.getMessage();
                String field = violation.getPropertyPath().toString();
                errors.put(field, message);
            }
            return errors;
        }
    }

    public static Map<String, String> validateList(Collection<?> collection) {
        if (null == collection) {
            throw new NullPointerException("collection cannot be null.");
        }

        if (collection.isEmpty()) {
            return Collections.emptyMap();
        }

        Map<String, String> errors = new LinkedHashMap<>();
        Iterator<?> iterator = collection.iterator();
        do {
            if (!iterator.hasNext()) {
                break;
            }
            Object object = iterator.next();
            errors = validate(object);
        } while (errors.isEmpty());

        return errors;
    }

    public static Map<String, String> validateObject(Object first, Object... objects) {

        if (objects != null && objects.length != 0) {
            List<Object> list = new LinkedList<>();
            list.add(first);
            list.addAll(Arrays.asList(objects));
            return validateList(list);
        } else {
            return validate(first);
        }
    }

    public static void check(Object param) {
        Map<String, String> errors = validateObject(param);
        if (MapUtils.isNotEmpty(errors)) {
            throw new IllegalArgumentException(errors.toString());
        }
    }
}
